package com.audiocn.dc;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.audiocn.Utils.Log;
import com.audiocn.manager.BaseManager;
import com.audiocn.poster.Application;
import com.audiocn.poster.Configs;
import com.audiocn.poster.R;

/**
 * 用来显示宝贝购买页面的DC
 */
public class PosterBuyDC extends BaseDC {

	private Button back;
	public WebView web;
	private WebSettings webSet;
	private ProgressDialog progress;
	
	private String url = null;
	
	public void recycle() {
		dismissDialog();
		web.stopLoading();
		web.clearCache(true);
		web.clearHistory();
		web.clearMatches();
		web.clearFormData();
		web.destroy();
		CookieManager cm = CookieManager.getInstance();
		cm.removeAllCookie();
		WebStorage ws = WebStorage.getInstance();
		ws.deleteAllData();
		web = null;
	}
	
	public PosterBuyDC(final Context context, int layoutId, final BaseManager manager) {
		super(context, layoutId, manager);
		back = (Button) this.findViewById(R.id.buy_back);
		back.setOnClickListener(this);
		web = (WebView) this.findViewById(R.id.buy_webView);
		webSet = web.getSettings();
		
		webSet.setSavePassword(false);
		webSet.setAllowFileAccess(true);
		webSet.setJavaScriptEnabled(true); 
		webSet.setBuiltInZoomControls(true);
		this.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
		web.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view,String url){
                return false;   
            }

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}
            
        }); 
		web.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (v != null) {
					v.requestFocus();
				}
				return false;
			}
		});
		web.setWebChromeClient(new WebChromeClient(){   
            public boolean onJsAlert(WebView view,String url,String message,final JsResult result){   
                Builder builder = new Builder(context);   
                builder.setTitle("提示对话框");   
                builder.setMessage(message);   
                builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener(){   
                    @Override  
                    public void onClick(DialogInterface dialog, int which) {   
                        result.confirm();   
                    }   
                });   
                builder.setCancelable(false);   
                builder.create();   
                builder.show();   
                return true;   
            }   
            public boolean onJsConfirm(WebView view,String url,String message,final JsResult result){   
                Builder builder = new Builder(context);   
                builder.setTitle("选择");   
                builder.setMessage(message);   
                builder.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener(){   
                    @Override  
                    public void onClick(DialogInterface dialog, int which) {   
                        result.confirm();   
                    }   
                });   
                builder.setNeutralButton(android.R.string.cancel, new AlertDialog.OnClickListener(){   
                    @Override  
                    public void onClick(DialogInterface dialog, int which) {   
                        result.cancel();   
                    }   
                });   
                builder.setCancelable(false);   
                builder.create();   
                builder.show();   
                return true;   
            }   
            public void onProgressChanged(WebView view,int newProgress){
            	if (newProgress == 100) {
            		Log.e("onProgressChanged", "complete");
					dismissDialog();
				}
                super.onProgressChanged(view, newProgress);   
            }   
        });   
		progress = new ProgressDialog(context);
		progress.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_BACKSLASH) {
					manager.sendEmptyMessage(Configs.STOP_ALL);
				}
				return false;
			}
		});
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return false;
	}
	
	@Override
	public void onClicked(View v) {
		if(Application.dcEngine.notAnimition()) {
			switch (v.getId()) {
			case R.id.buy_back:
				manager.sendMessage(manager.obtainMessage(110, 4, 0));
				break;
			default:
				break;
			}
		}
	}
	
	public void showDialog() {
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setIndeterminate(false);
		progress.setMessage("加载中.....");
		progress.setMax(1000);
		progress.setProgress(1);
		progress.show();
	}
	
	public void dismissDialog() {
		if (progress.isShowing()) {
			progress.dismiss();
		}
	}
	public void showTipDialog(String msg) {
		Toast.makeText(context, msg, 0).show();
	}
	public void loadURL(String url) {
		if(URLUtil.isNetworkUrl(url)) {
			if (this.url == null || this.url.trim().equals("") || !this.url.trim().equals(url)) {
				Log.e("oldUrl", "oldUrl(" + this.url + ")");
				if (this.url != null && !this.url.equals("") && !this.url.trim().equals(url)) {
					Log.e("loadURL", "webClear");
					web.stopLoading();
					web.clearCache(true);
					web.clearHistory();
					web.clearMatches();
					web.clearFormData();
					web.clearView();
					CookieManager cm = CookieManager.getInstance();
					cm.removeAllCookie();
					WebStorage ws = WebStorage.getInstance();
					ws.deleteAllData();
				}
				web.loadUrl(url);
				this.url = url;
			} else {
				dismissDialog();
			}
			Log.e("loadURL", "url(" + url + ")");
        } else {
        	showDialog("提示", "网址不合法");
        }
	}
	
	public void showDialog(String title, String msg) {
		Toast.makeText(context, msg, 0).show();
	}
}
